#include "telbook.h"

void write_entry(char *str[])
{
 int index = atoi(str[3]);
 //get index to write
 if(index < 1)
  { 
   printf("Invalid index\n");
   exit(0);
  }
 int fd;
 //file descriptor
 char action_buffer[40];
 //action to be written to log
 off_t offset;
 //offset where write occurs
 char read_buffer[20];
 char choice;
 //to check if entry at index already exist
 if((fd = open(str[2],O_RDWR,PERMS)) < 0)
  {
   perror("Failed to open:");
   exit(0);
  }
  
 sprintf(action_buffer,"%s %s","Opened File:",str[2]);
 //create record to write to log file
 write_log(action_buffer);

if((lseek(fd,0,SEEK_END))<((index)*SIZE))
   {//check if index exceeds file size
    printf("Index too large! Could not write\n");
    exit(0);
   }

 if ((offset = lseek(fd,(index-1)*SIZE,SEEK_SET)) == -1)
  {
   perror("Failed to seek in file:");
   exit(0);
  }
//check if entry already exists there 
if((read(fd,read_buffer,SUBSIZE))!=SUBSIZE)
    {
     perror("Failed to read:");
     exit(0);
    }

 if(read_buffer[0] != '\0')
   {
    printf("Entry Already Exists!Do you want to overwrite ?(y/n)\n");
    scanf("%c",&choice);
    if(choice == 'n')
       exit(0);
   }

if ((offset = lseek(fd,(index-1)*SIZE,SEEK_SET)) == -1)
  {
   perror("Failed to seek in file:");
   exit(0);
  }


 if((write(fd,str[4],strlen(str[4]))!=strlen(str[4])))
  {//write name entry
   perror("Failed to write:");
   exit(0);
  }
 if((write(fd,"\0",1))!=1)
  {//mark the end of entry
   perror("Failed to write:");
   exit(0);
  }
 if ((lseek(fd, (index-1)*SIZE+SUBSIZE , SEEK_SET)) == -1)
  {
   perror("Failed to seek in file:");
  }
 if((write(fd,str[5],strlen(str[5]))!=strlen(str[5])))
   {//write number entry
    perror("Failed to write in file:");
    exit(0);
   }
 
 if((write(fd,"\0",1))!=1)
  {//mark the end of entry
   perror("Failed to write:");
   exit(0);
  }
 //create action message for log
  sprintf(action_buffer,"%s %d %s %d","Wrote Content:",strlen(str[4])+strlen(str[5])+2,"bytes starting from position ",offset);
  //call log
  write_log(action_buffer);
  close(fd);
  sprintf(action_buffer,"%s %s","Closed File:",str[2]);
  write_log(action_buffer);

}

